import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webview_flutter/webview_flutter.dart';

const String h5String = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>通过URL向flutter传递参数</title>
</head>
<body>
    <button id="btn">hi h5 file</button>
</body>
</html>
''';

class FlutterH5JumpHtmlFile extends StatefulWidget {
  const FlutterH5JumpHtmlFile({super.key});

  @override
  State<FlutterH5JumpHtmlFile> createState() => _FlutterH5JumpHtmlFileState();
}

class _FlutterH5JumpHtmlFileState extends State<FlutterH5JumpHtmlFile> {
  late WebViewController controller;

  get _loadBtn => FilledButton(
    onPressed: () {
      _onLoadLocalFileExample(context);
    },
    child: const Text('加载H5', style: TextStyle(color: Colors.white)),
  );

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('通过loadFile的方式加载H5'), actions: [_loadBtn]),
      body: WebViewWidget(controller: controller),
    );
  }

  void _onLoadLocalFileExample(BuildContext context) async {
    final String path = await _prepareFile();
    debugPrint('path: $path');
    await controller.loadFile(path);
  }

  _prepareFile() async {
    final tmpDir = (await getTemporaryDirectory()).path;
    final File file = File(
      <String>{tmpDir, 'hi', 'index.html'}.join(Platform.pathSeparator),
    );
    await file.create(recursive: true);
    // 向文件写入h5 string数据
    await file.writeAsString(h5String);
    return file.path;
  }
}
